/*global define, console */

define(['angular', 'store'], function (angular, store) {
    "use strict";

    var factory = function ($location, $http, $httpParamSerializerJQLike, $rootScope, $state, $q, $ionicLoading, $ionicPopup, LocalCacheService, CacheFactory, CACHE_MAX_AGE) {


        CacheFactory('xcmCache', {
            deleteOnExpire: 'aggressive',
            maxAge: CACHE_MAX_AGE,
            storageMode: 'localStorage',
            storagePrefix: "tfzq."
        });

        return {
            productPageUrl: function (prodProfitMode, prodSource, prodType) {
                var url = null;
                if ("0,3".indexOf(prodProfitMode) > -1) {
                    url = "tab/product-item";
                } else if ("1" == prodProfitMode) {
                    url = "tab/product-item-QDII";
                } else if ("2" == prodProfitMode) {
                    url = "tab/product-item";
                    if ("1" == prodSource) {
                        url = "tab/product-item-otc";
                    }
                }else if ("4" == prodProfitMode) {
                    url = "tab/product-item";
                    if ("1" == prodSource) {
                        url = "tab/product-item-otc-float";
                    }
                }
                return url;
            },
            //prod_status 产品交易状态 0:正常交易 1:暂停交易 2:暂停申购 3:暂停赎回 4:产品认购 5：产品封闭
            //otc_status otc状态       0 未到销售时间 1 认购 2 已售罄 3 已过销售时间
            getOtcSellStatus: function (prod_status, otc_status) {
                //根据产品状况，控制按钮
                var sellStatus;
                if ("0,3,4".indexOf(prod_status) > -1) {
                    if ("1" == otc_status) {
                        sellStatus = 1; // 购买
                    } else if ("2,3".indexOf(otc_status) > -1) {
                        sellStatus = 3; // 已售罄
                    } else {
                        sellStatus = 2; //未到销售时间
                    }
                } else if ("2" == prod_status) {
                    sellStatus = 4; //暂停申购
                } else {
                    if ("2,3".indexOf(otc_status) > -1) {
                        sellStatus = 3;// 已售罄
                    } else {
                        sellStatus = 5; //暂停交易
                    }
                }
                return sellStatus;
            },
            getMinAmount: function (fund) {
                if (fund.prod_status == 4) {
                    return fund.prod_min_share;
                } else {
                    return fund.prod_min_subscribe;
                }
            },
            ajax: function (options) {
                if ((LocalCacheService.getAppContextName() == "gcs_tdx" || typeof TDXInterface!='undefined') && options.isSendData) {
                    return _TdxSendData(options);
                }else if (LocalCacheService.getAppContextName() == "gcs_ths"  && options.isSendData) {
                    return _ThsAjax(options);
                } else {
                    return _ajax(options);
                }
            },
            getUrlParams: function () {
                return $location.search();
            },
            position: function () {
                if (ionic.Platform.isIOS()) {
                    $('header').css("position", "absolute");
                    $('.service-tel').css("position", "absolute");
                }
            },
            jsGetAge: function (strBirthday) { //获取周岁
                var returnAge;
                var birthYear = strBirthday.substr(0, 4);
                var birthMonth = strBirthday.substr(4, 2);
                var birthDay = strBirthday.substr(6, 8);

                var d = new Date();
                var nowYear = d.getFullYear();
                var nowMonth = d.getMonth() + 1;
                var nowDay = d.getDate();

                if (nowYear == birthYear) {
                    returnAge = 0;//同年 则为0岁
                } else {
                    var ageDiff = nowYear - birthYear; //年之差
                    if (ageDiff > 0) {
                        if (nowMonth == birthMonth) {
                            var dayDiff = nowDay - birthDay;//日之差
                            if (dayDiff < 0) {
                                returnAge = ageDiff - 1;
                            } else {
                                returnAge = ageDiff;
                            }
                        } else {
                            var monthDiff = nowMonth - birthMonth;//月之差
                            if (monthDiff < 0) {
                                returnAge = ageDiff - 1;
                            } else {
                                returnAge = ageDiff;
                            }
                        }
                    } else {
                        returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
                    }
                }
                return returnAge;//返回周岁年龄
            },
            checkIdCard: function (num) {

                var bdate; // 生日
                num = num.toUpperCase();
                //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
                if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
                    //alert('输入的身份证号长度不对，或者号码不符合规定！\n15位号码应全为数字，18位号码末位可以为数字或X。');
                    return false;
                }
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                //下面分别分析出生日期和校验位
                var len, re;
                len = num.length;
                if (len == 15) {
                    re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
                    var arrSplit = num.match(re);
                    //检查生日日期是否正确
                    var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
                    var bGoodDay;
                    bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
                    if (!bGoodDay) {
                        //alert('输入的身份证号里出生日期不对！');
                        return false;
                    } else {
                        bdate = '19' + arrSplit[2] + arrSplit[3] + arrSplit[4];
                        //将15位身份证转成18位
                        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                        var nTemp = 0, i;
                        num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
                        for (i = 0; i < 17; i++) {
                            nTemp += num.substr(i, 1) * arrInt[i];
                        }
                        num += arrCh[nTemp % 11];
                        return bdate;
                    }
                }
                if (len == 18) {
                    re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
                    var arrSplit = num.match(re);
                    //检查生日日期是否正确
                    var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
                    var bGoodDay;
                    bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
                    if (!bGoodDay) {
                        //alert(dtmBirth.getYear());
                        //alert(arrSplit[2]);
                        //alert('输入的身份证号里出生日期不对！');
                        return false;
                    }
                    else {
                        bdate = arrSplit[2] + arrSplit[3] + arrSplit[4];
                        //检验18位身份证的校验码是否正确。
                        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                        var valnum;
                        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                        var nTemp = 0, i;
                        for (i = 0; i < 17; i++) {
                            nTemp += num.substr(i, 1) * arrInt[i];
                        }
                        valnum = arrCh[nTemp % 11];
                        if (valnum != num.substr(17, 1)) {
                            //alert('18位身份证的校验码不正确！应该为：' + valnum);
                            return false;
                        }
                        return bdate;
                    }
                }
                return false;
            },
            /**
             * 字符串是否为空
             * @param param
             * @returns {boolean}
             */
            isStrEmpty: function (param) {
                if (null == param || "undefined" == typeof(param) || "" == $.trim(param)) {
                    return true;
                }
                return false;
            },
            controlNum: function (param, num) {
                if (null == param || "undefined" == typeof(param) || "" == param || isNaN(param)) {
                    return "--";
                } else {
                    return parseFloat(parseFloat(param).toFixed(num));
                }
            },
            /**
             * 展示普通弹出框
             * @param options(Json Object){
		 * 		message:弹出层内容 jQuery对象或字符串
		 * 		fixed：是否固定最小高度和宽度，默认true 表示需要固定
		 * 			以下参数只在 fixed 为true时有效
		 *			width:最小宽度 单位：像素
		 * 			height：最小高度 单位：像素
		 * 		}
             * @returns
             */
            getSource: function () { //渠道统计使用
                var source;
                if (ionic.Platform.isAndroid()) {
                    source = "ANDROID";
                } else if (ionic.Platform.isIOS()) {
                    source = "IOS";
                } else if (this.isWeixin()) {
                    source = "WEIXIN";
                } else {
                    source = "OTHER";
                }
                return source;
            },
            showAlert: function (options) {
                var $m = options.message;
                var opts = $.extend({}, options, {message: $m});
                if ($.type($m) === "object") {//对象
                    var css = position(options);
                    $.extend(opts, {css: css});
                }
                show(opts,1);
            },
            showLogout: function (options) {
                var $m = options.message;
                var opts = $.extend({}, options, {message: $m});
                if ($.type($m) === "object") {//对象
                    var css = position(options);
                    $.extend(opts, {css: css});
                }
                show(opts,2);
            },
            showNotice: function (str, key) {
                var contents = str.split("&&");
                if (!key || (!localStorage[key] || localStorage[key] != 1)) {
                    $ionicPopup.show({
                        cssClass: "kDialog",
                        template: contents[1],
                        title: contents[0],
                        buttons: [
                            {text: '关闭'},
                        ]
                    }).then(function () {
                        if (key) {
                            localStorage[key] = 1;
                        }
                    });
                }

            },
            showConfig: function (options) {
                return _showConfig(options);
            },
            //完成后弹出提示框
            showComplete: function (templateUrl, btnText, url) {
                $ionicPopup.show({
                    cssClass: "yDialog",
                    templateUrl: templateUrl,
                    buttons: [{
                        text: btnText,
                        onTap: function () {
                            $state.go(url);
                        }
                    }]
                });
            },
            showConfirm: function (options, cancel, confirm) {
                $ionicPopup.show({
                    cssClass: "kDialog",
                    template: options.message,
                    title: options.title ? options.title : '提示',
                    buttons: [{
                        text: options.btn1Text ? options.btn1Text : '取消',
                        onTap: function () {
                            cancel();
                        }
                    }, {
                        text: options.btn2Text ? options.btn2Text : '确定',
                        onTap: function () {
                            confirm();
                        }
                    }]
                });
            },
            /**
             * 是否是购买体验活动
             */
            isBuyExperience: function () {
                var lcty_state = LocalCacheService.get("lcty_state");
                if (lcty_state && lcty_state.stateName) {
                    return true;
                }
                return false;
            },
            /**
             * 判断是否为微信
             * @returns {boolean}
             */
            isWeixin: function () {
                var ua = navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == "micromessenger") {
                    return true;
                } else {
                    return false;
                }
            },
            /**
             * 获取错误信息
             * @param result
             * @returns {*}
             */
            getErrorInfo: function (result) {
                return _getErrorInfo(result);
            },
            stringToDate: function (dateString) {
                var d = new Date();
                d.setFullYear(parseInt(dateString.substr(0, 4)), parseInt(dateString.substr(4, 2)) - 1, parseInt(dateString.substr(6, 2)));
                return d;
            },
            formatDate: function (date) {
                if (null == date || "" == date || "undefined" == typeof(date)) {
                    return '--';
                }
                date = date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + date.substr(6, 2);
                return date;
            },
            formatDate2: function (date) {
                if (null == date || "" == date || "undefined" == typeof(date)) {
                    return '--';
                }
                var m = date.substr(4, 2) < "10" ? date.substr(5, 1) : date.substr(4, 2);
                var d = date.substr(6, 2) < "10" ? date.substr(7, 1) : date.substr(6, 2);
                return m + "月" + d + "日";
            },
            formatTime: function (time) {
                if (null == time || "" == time || "undefined" == typeof(time)) {
                    return '--';
                }
                var d = time.substr(0, 4) + "-" + time.substr(4, 2) + "-" + time.substr(6, 2);
                var t = time.substr(8, 2) + ":" + time.substr(10, 2) + ":" + time.substr(12, 2);
                return d + " " + t;
            },
            checkRegex: function (regex, value) {
                var re = new RegExp(regex);
                if (re.test($.trim(value))) {
                    return true;
                } else {
                    return false;
                }
            },
            trim: function (str) {
                var regExp = new RegExp(" ", "g");
                if (!str) {
                    return null;
                }
                if (angular.isString(str)) {
                    return str.replace(regExp, "");
                } else {
                    return str.toString().replace(regExp, "");
                }
            },
            getPrevDate: function () {
                var d = new Date();
                d.setDate(d.getDate() - 1);
                return d.getMonth() + 1 + "月" + d.getDate() + "日";
            }
        };
        //----------------内部方法------------------------------

        function _TdxSendData(options) {
            var httpOption = {
                method: options.type || "POST", serverName: (options.basePath || $rootScope.basePath),
                requestPath: options.url, params: options.data || {}, headers: {}
            };
            httpOption.headers["User-Agent"] = navigator.userAgent;
            var UUID = store.get('UUID');
            if (UUID) {
                httpOption.headers["UUID"] = UUID;
            }
            var userCache = CacheFactory.get('UserCache');
            var user = userCache.get('user');
            if (user) {
                httpOption.headers["TOKEN"] = user.token;
            }
            var deferred = $q.defer();
            TDXInterface.sendData({"tdxFuncData": JSON.stringify(httpOption),"PasswordSessionID":options.PasswordSessionID}, function (data) {
                try {
                    var result = JSON.parse(data.text);
                    if (result && result.error_no == "0") {
                        deferred.resolve(result.data);
                    } else {
                        if (result.error_no == "AH-10001") {
                            store.remove('user');
                            $rootScope.$emit("userIntercepted", "sessionOut");
                            deferred.reject(result);
                        } else {
                            if (!options.isReject) {
                                callException(null, result, options.styleType);
                            }
                            deferred.reject(result);
                        }
                        $ionicLoading.hide();
                    }
                }catch(er){
                    deferred.reject({error_no:-102, error_info:'获取超时'});
                }
            });
            return deferred.promise;
        }

        function _ajax(options) {
            //var url = (options.basePath || $rootScope.basePath) + options.url;
            var url= options.basePath=="wt" ?  options.url : (options.basePath || $rootScope.basePath) + options.url;
            var httpOption = {method: options.type || "post", url: url, "timeout": 35000};
            if (httpOption.method == "post") {
                httpOption.data = options.data || {};
            } else {
                var pString = $httpParamSerializerJQLike(options.data || {});
                httpOption.url += pString ? "?" + pString : "";
                httpOption.offline = true;
                if (options.cache) { //缓存
                    httpOption.cache = CacheFactory.get('xcmCache');

                    var cacheDate = httpOption.cache.get(httpOption.url);
                    if (cacheDate) {
                        if (cacheDate[1] && angular.fromJson(cacheDate[1]).error_no != "0") {
                            httpOption.cache.remove(httpOption.url);
                        } else if (angular.isFunction(cacheDate.then)) {
                            cacheDate.then(function (data) {
                                if (data && data.data && angular.fromJson(data.data).error_no != "0") {
                                    httpOption.cache.remove(httpOption.url);
                                }
                            });
                        }
                    }
                }
            }
            var deferred = $q.defer();
            $http(httpOption).success(function (result, status, headers, config) {
                if (result && result.error_no == "0") {
                    deferred.resolve(result.data);
                } else {
                    if (!options.isReject) {
                        callException(null, result, options.styleType);
                    }
                    deferred.reject(result);
                    $ionicLoading.hide();
                }
            }).error(function (data, status, headers, config) {
                if (XMLHttpRequest.readyState == 4) {
                    if (XMLHttpRequest.status == "200" || textStatus == "OK") {
                        if (!options.isReject) {
                            callError(null, XMLHttpRequest.responseText);
                        }
                    } else {
                        _showConfig({message: "调用数据失败,请稍后再试."});
                    }
                }
                deferred.reject(XMLHttpRequest.responseText);
                $ionicLoading.hide();
            });

            return deferred.promise;
        }

    function _ThsAjax(options) {
        var url = (options.basePath || $rootScope.basePath) + options.url;
        options.data.url = url;
        var deferred = $q.defer();
        options.data.userAgent = navigator.userAgent;
        ThsTools.sdkLogin(options.data, function(data) {
            if (data && data.error_no == "0") {
                deferred.resolve(data.result);
            } else {
                if (!options.isReject) {
                    callException(null, data, options.styleType);
                }
                deferred.reject(data);
                $ionicLoading.hide();
            }
        })


        return deferred.promise;
    }
        /**
         * 异常信息返回时调用，显示错误信息
         * @param result(JSON obj)
         */
        function callException(failure, result, styleType) {
            if (failure) {
                failure(result);
            } else {
                if (styleType && styleType == 1) {
                    show({message: _getErrorInfo(result)},1);
                } else {
                    _showConfig({message: _getErrorInfo(result)});
                }
            }

        }

        /**
         * 出现异常时调用异常信息
         * @param failure(Function) 失败时回调方法
         * @param errorMessage(String) 异常信息
         *
         */
        function callError(failure, errorMessage) {
            if (failure) {
                failure(errorMessage);
            } else {
                _showConfig({message: errorMessage});
            }
        }

        /**
         * 定位弹出层位置
         * @param options(Json Object) 同 showAlert 参数说明
         * @returns Json Object {
	 * 		left : 左边距离 单位：像素,
	 *		width : 宽度 单位：像素,
	 *		height: 高度 单位：像素,
	 *		top : 距离顶部距离 单位：百分比,
	 * }
         */
        function position(options) {
            var $m = options.message;
            //是否固定最小宽度及高度
            var fixed = options.fixed || true;
            //元素宽度
            var _popWidth = $m.width();
            //元素高度
            var _popHeight = $m.height();
            if (fixed) {//处理固定情况的高度及宽度
                var _minWidth = options.width || 300;
                var _minHeight = options.height || 150;
                _popWidth = _popWidth < _minWidth ? _minWidth : _popWidth;
                _popHeight = _popHeight < _minHeight ? _minHeight : _popHeight;
            }
            //计算 高度和宽度
            var _widowWidth = $(window).width();
            //Loading为要显示的div
            var _popLeft = (_widowWidth - _popWidth) / 2;
            var _windowHeight = $(window).height();
            var _top = (_windowHeight - _popHeight) / 2;
            //最小距离顶部30px;
            _top = _top < 30 ? 30 : _top;
            var _popTop = Math.floor(_top / _windowHeight * 100);
            _popTop = _popTop < 20 ? 20 : _popTop;
            return {
                left: _popLeft + 'px',
                width: _popWidth + 'px',
                height: _popHeight + 'px',
                top: _popTop + '%'
            };
        }

        /**
         * 弹出框
         * @param options
         */
        function show(options, btype) {
            if(btype==1) {
                TF.Bubble.show(options.message);
            }
            else{
                TF.BubbleOut.show(options.message);
            }
            if (options.onUnblock) {
                options.onUnblock();
            }

//            var myPopup = $ionicPopup.alert({
//                cssClass: 'popup-head-hide ',
//                template: options.message,
//                buttons: []
//            });
//            $timeout(function() {
//                myPopup.close();
//            }, 2000);
        }

        function _showConfig(options) {
            return $ionicPopup.show({
                cssClass: "kDialog",
                template: options.message,
                title: options.title ? options.title : '提示',
                buttons: [
                    {text: (options.okText ? options.okText : '确定')}
                ]
            });
        }

        /**
         * 获取错误信息
         * @param result
         */
        function _getErrorInfo(result) {
            if (result.error_info && result.error_info!='null') {
                return result.error_info;
            }
            if (typeof  result == "string") {
                return result;
            } else if (typeof result == "object") {
                return result.errorMessage;
            }
            return "未知错误";
        }
    };

    factory.$inject = ['$location', '$http', '$httpParamSerializerJQLike', '$rootScope', '$state', '$q',
        '$ionicLoading', '$ionicPopup', 'LocalCacheService', 'CacheFactory', 'CACHE_MAX_AGE'];
    return factory;
});